package cn.gene.timeyan.ams.webapi.service.impl;

import cn.gene.timeyan.ams.service.IAuditService;
import cn.gene.timeyan.ams.webapi.mapper.AuditMapper;
import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.pojo.admin.dto.AuditDTO;
import cn.gene.timeyan.pojo.admin.model.Audit;
import cn.gene.timeyan.pojo.admin.vo.AuditVO;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import static cn.gene.timeyan.common.restful.ResponseCode.INTERNAL_SERVER_ERROR;

/**
 * 审查   服务实现类*
 *
 * @author LWG
 * @date 2022/7/21 17:44
 * @since 1.0.0@gene.cn
 */
@Slf4j
@Service
public class AuditServiceImpl implements IAuditService {

    @Autowired
    private AuditMapper auditMapper;

    @Override
    public void addAudit(AuditDTO auditDTO) {
        log.trace("auditDTO----->>>", auditDTO);


        //查看所有的未审核信息(审核状态为0)
        List<AuditVO> auditVOS = auditMapper.selectAuditDTOByHandleState(auditDTO);

        //查看所有的已审核信息(审核状态为1)的用户id
        List<AuditVO> states = auditMapper.selectHandleStateByUserId(auditDTO.getUserId(), auditDTO.getSourceId(), auditDTO.getModuleId());

        //如果查询结果不为空，说明全部都未审核
        if (auditVOS.size() > 0) {
            log.info("提交成功，开始审核");
            //审核未审核信息（修改状态，审核时间，及更改时间）
             auditMapper.updateCheckStateAndCheckTimeByUserId(auditDTO.getUserId(), auditDTO.getSourceId());

        } else if (states.size()>0) {
            log.error("在审核中");
            throw new TimeyanServiceException(INTERNAL_SERVER_ERROR, "相同信息已在审核中！");
        } else {
            //说明相同内容没审核过，开始向审核表添加信息
            log.trace("开始向审核表添加信息");

            Audit audit = new Audit();

            BeanUtils.copyProperties(auditDTO, audit);

            //补全对象属性
            LocalDateTime now = LocalDateTime.now();
            audit.setCheckTime(now);
            audit.setCreateTime(now);
            audit.setUpdateTime(now);
            audit.setFoundTime(now);
            //插入数据
            int rows = auditMapper.insertAudit(audit);

            //判断结果是否为1
            if (rows != 1) {
                throw new TimeyanServiceException(INTERNAL_SERVER_ERROR, "添加审核信息失败，服务器忙，请稍后再次尝试！");
            }
        }
    }
}

